<template>
    <BPTable ref='tableRef' align='center' row-key='id' :columns='columns' :api='pageApi' :buttons='buttons' :rowSelection="false">
        <template #attrNames="{ record }">
            <template v-if="record.attrNames">
                <template v-for="(name, i) in record.attrNames" :key="i">
                    <a-tag color="green">{{ name }}</a-tag>
                </template>
            </template>
        </template>
        <template #settingNames="{ record }">
            <template v-if="record.settingNames">
                <template v-for="(name, i) in record.settingNames" :key="i">
                    <a-tag color="green">{{ name }}</a-tag>
                </template>
            </template>
        </template>
    </BPTable>

    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit' @close="resetForm">
        <a-form ref='formRef' layout="vertical" :rules="rules" :label-col='{span : 5}' :model='formData'>
            <a-form-item style='display:none' name='id'>
                <a-input type='hidden' v-model:value='formData.id' />
            </a-form-item>
            <a-form-item :label="$c('name')" name="name">
                <a-input v-model:value='formData.name' />
            </a-form-item>
            <a-form-item label="属性" name="attrs">
                <a-select v-model:value='formData.attrs' mode="multiple" :options="settingAttrOptions"></a-select>
            </a-form-item>
            <a-form-item label="设置项" name="settings">
                <a-select v-model:value='formData.settings' mode="multiple" :options="settingAttrOptions"></a-select>
            </a-form-item>
            <a-form-item :label="$c('remark')" name="remark">
                <a-input v-model:value='formData.remark' />
            </a-form-item>
        </a-form>
    </BDialog>

</template>

<script lang='ts' setup>
    import { optionsApi } from '@/api/devices/DeviceSettingAttr'
    import { pageApi, deleteApi, saveApi } from '@/api/devices/Model'
    import { useI18nStore } from '@/store/i18n'
    import { message, Modal } from 'ant-design-vue'
    import { ref } from 'vue'
    import { Rule } from 'ant-design-vue/lib/form';


    const activeKey = ref(1)
    const i18n = useI18nStore()
    const visible = ref(false)

    const tableRef = ref()
    const formRef = ref()
    const dialogTitle = ref()
    

    const formData = ref<{attrs : number[]; settings:number[]; [key:string]:any}>({
        id : 0,
        name : '',
        attrs : [],
        settings : [],
        remark : '',
    })




    const settingAttrOptions = ref<{value:number;label:string}[]>([])

    function getsettingAttrOptions() {
        if(settingAttrOptions.value.length == 0) {
            optionsApi().then(res => {
                res.data.forEach(row => {
                    settingAttrOptions.value.push({value : row.id, label : i18n.t(row.name)})
                })
            })
        }
        
    }

    
    const rules: Record<string, Rule[]> = {
        name : [
            {
                required : true,
                message : i18n.concat('please', 'input', 'name')
            }
        ]
    };

    

    const buttons = ref<SearchButton[]>([])
    buttons.value.push({
        button : 'add',
        func : () => {
            getsettingAttrOptions()


            dialogTitle.value = i18n.t('add')
            // formData.value.ports.splice(0)
            // addPort()
            visible.value = true
        }
    })


  
    function resetForm() {
        formRef.value.clearValidate()
        formRef.value.resetFields()
    }
    
    async function submit() {
        try {
            let { id, ...params} = await formRef.value.validate()
        
            if(id) {
                params.id = Number(id)
            }

            
            const res = await saveApi(params)
            if(res.success) {
                resetForm()
                visible.value = false
                message.success(i18n.t('saveSuccess'))
                tableRef.value.load()
            }else {
                Modal.error({
                    title : res.msg
                })
            }
        } catch (error:any) {
            if(error.errorFields) {
                if(activeKey.value == 2) {
                    message.error(error.errorFields[0].errors[0])
                    activeKey.value = 1
                }
                
            }
        }
    }


    

    const columns = ref<Column[]>([
        {
            title : i18n.t('name'),
            dataIndex : 'name',
            align : 'center',
           
            translate : true,
            inSearch : true
        },

        {
            title : '属性',
            dataIndex : 'attrNames',
            align : 'center',
            
            inSearch : true,
        },

        {
            title : '设置项',
            dataIndex : 'settingNames',
            align : 'center',
            
            inSearch : true,
        },


        {
            title : i18n.t('remark'),
            dataIndex : 'remark',
           
            align : 'center',
        },

        {
            title : i18n.t('action'),
            dataIndex : '$action',
            align : 'center',
           
            $edit : (row) => {
                dialogTitle.value = i18n.t('edit')
                getsettingAttrOptions()
                for(let k in formData.value) {
                    if(k == 'settings') {
                        formData.value[k] = !row[k] ? {} : row[k]
                    }else {
                        formData.value[k] = row[k]
                    }
                    
                    
                }

                visible.value = true
            },

            $delete :  async (row) => {
                const res = await deleteApi(row.id)
                if(res.success) {
                    message.success(i18n.t('deleteSuccess'))
                    tableRef.value.load()
                }else {
                    message.error(res.msg)
                }
            }
        }
    ])


    

    
</script>

<style lang='scss' module>
    .portRow{
        display: flex;
        align-items: center;

        .input{
            flex: 1;
        }
        .minus{
            margin-left: 10px;
            color: #999;
            cursor: pointer;
            font-size: 24px;
        }
    }

</style>